﻿var SeasonValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var SeasonAutoComElem = null;
var SeasonAutoComElemVal = null;
var SeasonTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("ManageSeasons") != -1) {
        jQuery.validator.addMethod("ManageSeasonRequireds", jQuery.validator.methods.required, Messages["ManageSeasonRequireds"]);
        jQuery.validator.addMethod("ManageSeasonMaxLength20", jQuery.validator.methods.maxlength, Messages["ManageSeasonMaxLength20"]);
        jQuery.validator.addMethod("ManageSeasonMaxLength50", jQuery.validator.methods.maxlength, Messages["ManageSeasonMaxLength50"]);
        jQuery.validator.addMethod("ManageSeasonDate", jQuery.validator.methods.datePicker, Messages["ManageSeasonDate"]);
        $.validator.addClassRules({
            Required: {
                ManageSeasonRequireds: true,
            },
            MaxLength20: {
                ManageSeasonMaxLength20: 20,
            },
            MaxLength50: {
                ManageSeasonMaxLength50: 50,
            },
            Date: {
                ManageSeasonDate: true,
            },
        });

        $('#LoadSeasonDetailsForm').validate();
        LoadSeasonGrid();
    }
});
$(document).on('change', '.ChangedSeasonElements', function () {
    $('#SeasonDetailsSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.SeasonAddElementChange', function () {
    $('#SeasonAddBtn').addClass('BackColorRed');
});
function AddNewSeason() {
    SeasonValidationClientSideHide = false;
    $.ajax({
        url: urls["SeasonAddNewSeason"],
        type: 'GET',
        success: function (data) {
            $("#AddNewSeasonDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            AddNewSeasonPopUp("AddNewSeasonDiv");
            InitSeasonDetailsDataCalendars();
        }
    });
}
$(document).on('click', '#SeasonMoreBtn', function () {
    PageNumber = PageNumber + 1;
    LoadSeasonGrid();
});
$(document).on('click', '#SeasonSearchBtn', function () {
    IsSearchView = true;
    LoadSeasonGrid();
});
function AddNewSeasonPopUp(PopUpDiv) {
    $.colorbox({
        width: "600px",
        height: "300px",
        inline: true,
        href: "#" + PopUpDiv,
        onComplete: function () {
            $("#" + PopUpDiv).show();
            InitAddSeasonDetailsDataCalendars();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#SeasonAddBtn', function () {
    var $form = $('#AddNewSeasonForm');
    if ($form.valid()) {
        SeasonValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#SeasonAddBtn').removeClass('BackColorRed')
                jAlert("Data SuccessFully Saved:", "Successful");
                $('#cboxClose').click();
                LoadSeasonGrid();
            }
        });
    }
    else
        SeasonValidationClientSideHide = true;
});

$(document).on('click', '#SeasonDetailsSaveBtn', function () {
    var $form = $('#LoadSeasonDetailsForm');
    if ($form.valid()) {
        if ($form[0].length > 0) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error");
                },
                complete: function () {
                    $('#SeasonDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    LoadSeasonGrid();
                }
            });
        }
        else
        {
            jAlert("You have not data to save:", "Attention!");
        }
    }
});
function InitSeasonDetailsDataCalendars() {
    $(".SeasonDeteilsDataCalendarFrom").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 5
            });
        },
        onClose: function (selectedDate) {
          $(this).parent().parent().find(".SeasonDeteilsDataCalendarTo").datepicker("option", "minDate", selectedDate);
        }
    });
    $(".SeasonDeteilsDataCalendarTo").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 5
            });
        },
        onClose: function (selectedDate) {
            $(this).parent().parent().find(".SeasonDeteilsDataCalendarFrom").datepicker("option", "maxDate", selectedDate);
        }
    });
}
function InitAddSeasonDetailsDataCalendars() {
    $(".AddSeasonDeteilsDataCalendarFrom").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 99999999,
            });
        },
        onClose: function (selectedDate) {
            $(".AddSeasonDeteilsDataCalendarTo").datepicker("option", "minDate", selectedDate);
        }
    });
    $(".AddSeasonDeteilsDataCalendarTo").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 99999999,
            });
        },
        onClose: function (selectedDate) {
            $(".AddSeasonDeteilsDataCalendarFrom").datepicker("option", "maxDate", selectedDate);
        }
    });
}
function LoadSeasonGrid() {
    var ManageSeasonsGridViewModel = {
        SeasonCodeText: $("#SeasonCodeText").val(),
        SeasonDescriptionText: $("#SeasonDescriptionText").val(),
        IsCurrentSearch: $("#IsCurrentSearch").val(),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
    };

    var DTO = JSON.stringify(ManageSeasonsGridViewModel);
    $.ajax({
        url: urls["SeasonLoadSeasonsGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#ManageSeasonGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            InitSeasonDetailsDataCalendars();
        }
    });
}

// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (SeasonTimerId == null) {
        SeasonAutoComElem = $(this).attr('id');
        SeasonAutoComElemVal = $("#" + SeasonAutoComElem).val();
        SeasonTimerId = setInterval(function () {

            var keyword = $("#" + SeasonAutoComElem).val();
            if (keyword == SeasonAutoComElemVal) {
                var PropName = "";
                if (SeasonAutoComElem.indexOf("SeasonCodeText") != -1)
                    PropName = "SeasonCodeText";
                if (SeasonAutoComElem.indexOf("SeasonDescriptionText") != -1)
                    PropName = "SeasonDescriptionText";

                var position = $("#" + SeasonAutoComElem).offset();
                position.top = position.top + $("#" + SeasonAutoComElem).height() + 5;
                $.ajax({
                    url: urls["SeasonAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + SeasonAutoComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(SeasonTimerId);
                        SeasonTimerId = null;
                    }
                });
            }
            else
                SeasonAutoComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + SeasonAutoComElem).val(val);
    if (SeasonAutoComElem.indexOf("SeasonCodeText") != -1)
        $("#" + SeasonAutoComElem).next().val(key);
    if (SeasonAutoComElem.indexOf("SeasonDescriptionText") != -1)
        $("#" + SeasonAutoComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}
$(document).on('change', '.SeasonAddElementChange', function () {
    $('#SeasonAddBtn').addClass('BackColorRed');
});
var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#SeasonAddBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddNewSeasonForm").empty();
                LoadSeasonGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddNewSeasonForm").empty();
        LoadSeasonGrid();
        originalClose();
    }
};
$(document).on('change', '.ForValidation', function () {
    if ($(this).valid)
        $(this).removeClass('table_inputs_Unvalidated');
    if ($(this).closest("form").valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            if ($(this).valid())
                $(this).removeClass('table_inputs_Unvalidated');
        });
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
});
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (SeasonValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});
